#include "myfile.h"
#include "properties.h"
#include <stdlib.h>
#include <string.h>

static void nextLine(MYFile fd)
{
  char c;

  while(readFile(fd,&c,sizeof(char))==sizeof(char))
  {
    if(c=='\n') break;
  }
}

static int readVal(MYFile fd, char *buf)
{
  int i;
  char c;

  for(i=0; i<MAX_PROPERTY_SIZE; i++)
  {
    int rdSz = readFile(fd,&c,sizeof(char));

    if(rdSz<sizeof(char)) return 0;
    if( (rdSz==0) || (c=='\n') )
    {
      buf[i]=0;
      return i+1;
    }
    else
    {
      buf[i]=c;
    }
  }

  return 0;
}

char *getPropertyValue(char *fname, char *propertyName)
{
  int i=0;
  char buf[MAX_PROPERTY_SIZE+1];
  char *result = 0;
  MYFile fd = openFile(fname,MRead);

  if(fd<0) return 0;

  while(readFile(fd,buf,sizeof(char))==sizeof(char))
  {
    if( (propertyName[i]==0) && (buf[0]=='=') )
    {
      int sz = readVal(fd, buf);
      result = malloc(sizeof(char)*sz);
      if(result) memcpy(result,buf,sz);
      break;
    }

    if(buf[0]!=propertyName[i])
    {
      i=0;
      if(buf[0]!='\n') nextLine(fd);
    }
    else ++i;
  }

  close(fd);
  return result;
}

char *getPropertyName(char *fname, unsigned int propertyNum)
{
  int i=0;
  unsigned int num=0;
  char c,buf[MAX_PROPERTY_SIZE+1];
  char *result = 0;

  MYFile fd = openFile(fname,MRead);

  if(fd<0) return 0;

  while(readFile(fd,&c,sizeof(char))==sizeof(char))
  {
    if(c=='=')
    {
      if(num==propertyNum)
      {
        buf[i] = 0;
        char *name = malloc(sizeof(char)*(i+1));
        if(name) memcpy(name, buf, i+1);
        return name;
      }

      i=0;
      ++num;
      nextLine(fd);
      continue;
    }
    if(c=='\n')
    {
      i=0;
      continue;
    }
    buf[i] = c;
    ++i;
  }

  return 0;
}

Property *getProperty(char *fname, unsigned int propertyNum)
{
  char *name = getPropertyName(fname, propertyNum);
  Property *result = 0;

  if(name)
  {
    result = (Property *) malloc(sizeof(Property));
    if(!result) goto ERR;

    result->name = name;
    result->value = getPropertyValue(fname, name);
  }

  return result;

ERR:
  if(name) free(name);
  return 0;
}

void delProperty(Property *p)
{
  if(p)
  {
    if(p->name) free(p->name);
    if(p->value) free(p->value);
    free(p);
  }
}
